<template>
    <!-- 大棚 -->
    <view>
        <view>
            <uni-section title="消息列表" type="line">
            </uni-section>

			<!-- 报警消息弹框 -->
			<uni-popup ref="alertPopup" type="top">
			  <uni-popup-dialog
			    type="error"
			    title="报警消息"
			    :content="alertMessage"
			    :duration="0"
			    @confirm="closeAlert"
			  ></uni-popup-dialog>
			</uni-popup>

            <view class="message-container">
                <!-- 动态渲染消息 -->
                <view v-for="message in messages" :key="message.id" class="message-item">
                  <!-- 显示图片 -->
                  <image class="avatar" :src="getMessageImageUrl(message)" mode="aspectFill"></image>
                  <view class="message-content-wrapper">
                    <view class="message-title">
                      <!-- 修改为 createBy -->
                      <!-- <text class="message-receive-name">{{ message.createBy }}</text> -->
					  <text class="message-receive-name">一号设备</text>
                      <!-- 修改为 createTime -->
                      <text class="message-date">{{ message.createTime }}</text>
                    </view>
                    <!-- 修改为 messageDescribe -->
                    <text class="message-content">{{ message.messageDescribe }}</text>
                  </view>
                </view>
                <view class="footer">
                    <text class="footer-text">—— 我是有底线的 ——</text>
                </view>
            </view>
        </view>
    </view>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import request from '/utils/request';

// 报警消息相关
const alertMessage = ref('');
const alertPopup = ref(null);
const messageQueue = ref([]) // 消息队列
let isShowingAlert = false // 标记当前是否正在显示弹窗
let popupInstance = null

// 显示弹窗
const showAlert = () => {
  if (messageQueue.value.length === 0 || isShowingAlert) return

  isShowingAlert = true
  const currentMessage = messageQueue.value.shift()
  alertMessage.value = `${currentMessage.messageDescribe}`
  alertPopup.value?.open();

  // 创建新的弹窗实例
    popupInstance = alertPopup.value.open('top')

    // 3秒后自动关闭并显示下一条
    setTimeout(() => {
      closeAlert()
    }, 3000)
};

// 关闭弹窗时触发下一条消息
const closeAlert = () => {
  if (popupInstance) {
    popupInstance.close()
  }

  isShowingAlert = false
  // 延迟一小段时间再显示下一条，确保动画完成
  setTimeout(() => {
    showAlert()
  }, 300)
}

// 监听WebSocket消息
onMounted(() => {
  uni.$on('websocket:message', (message) => {
	console.log("home:", message);
    // 将新消息加入队列
      messageQueue.value.push(message)
      // 如果没有正在显示的弹窗，立即显示
      if (!isShowingAlert) {
        showAlert()
      }
  });
});

import { API_BASE_URL } from "/env_config.js"
const baseUrl=API_BASE_URL ;
// 消息数据
const messages = ref([]);
// 排序后的消息数据
const sortedMessages = ref([]);
// 当前页码
const currentPage = ref(1);
// 每页数量
const pageSize = ref(10);

// 解析图片 URL 的函数
const getMessageImageUrl = (message) => {
  const params = message.messageSpecialInfo
      .replace(/\{|}/g, '')
      .split(', ')
      .reduce((acc, item) => {
        const [key, value] = item.split('=');
        acc[key] = value;
        return acc;
      }, {});

  // 检查 params.url 是否存在且不为空
  if (!params.url) {
    return "图片加载失败";
  }

  return baseUrl+params.url;
};

const fetchMessages = async () => {
  try {
    const res = await request({
      url: '/admin/iotDeviceMessage/page',
      method: 'GET',
      data: {
        current: currentPage.value,
        size: pageSize.value
      }
    });
    console.log('返回数据：', res.data.data);
    if (res.statusCode === 200) {
      messages.value = res.data.data.records;
	  // 对消息数据按 createTime 进行降序排序
	  sortedMessages.value = messages.value.sort((a, b) => {
	    return new Date(b.createTime) - new Date(a.createTime);
	  });
      console.log('信息如下',res.data);
    } else {
      console.error('请求失败:', res.errMsg);
    }
  } catch (error) {
    console.error('请求出错:', error);
  }
};

onMounted(() => {
    fetchMessages();
});
</script>

<style lang="scss">

/* 弹框样式 */
.uni-popup-dialog {
  width: 100% !important;
  max-width: 100% !important;
}

.uni-popup-dialog-title {
  font-size: 18px;
  font-weight: bold;
  color: #ff0000;
}

.uni-popup-dialog-content {
  font-size: 16px;
  padding: 10rpx;
}

/* 测试按钮样式 */
.test-button {
  position: fixed;
  bottom: 50px;
  right: 20px;
  z-index: 999;
}

.test-button button {
  background-color: #ff0000;
  color: white;
  border-radius: 50%;
  width: 50px;
  height: 50px;
  font-size: 10px;
}


.message-container {
    padding: 20px;
}

.message-header {
    display: flex;
    justify-content: center;
    align-items: center;
    margin-bottom: 20px;
    // border-bottom: 1px solid #999; // 添加底部边框
}

.header-text {
    font-size: 19px;
    font-weight: bold;
}

.message-item {
    display: flex;
    align-items: flex-start;
    margin-bottom: 10px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    border-radius: 5px;
    background-color: white;
    padding: 10px;
}

.avatar {
    width: 40px;
    height: 40px;
    border-radius: 2px;
    margin-right: 10px;
    flex-shrink: 0;
}

.message-content-wrapper {
    flex: 1;
}

.message-title {
    display: flex;
    justify-content: space-between;
    font-size: 15px;
}

.message-date {
    font-size: 12px;
    color: #999;
    margin-bottom: 5px;
    display: block;
}

.message-content {
    font-size: 12px;
    color: #707070;
}

.footer {
    position: fixed;
    bottom: 50px; /* 调整这个值以适应底部菜单的高度 */
    left: 0;
    right: 0;
    text-align: center;
    padding: 10px 0;
}

.footer-text {
    font-size: 12px;
    color: #999;
}
</style> 